#!/usr/bin/python
# author Yu
# 2023年06月19日
import socket


from tran import TransCode
import select


class Server:
    def __init__(self, ip, port):
        self.addr = (ip, port)
        self.trans = TransCode()
        self.user_dict={}

    def run(self):
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind(self.addr)
        server_socket.listen(10)
        epoll = select.epoll()
        epoll.register(server_socket.fileno(), select.EPOLLIN)
        while True:
            events = epoll.poll(-1, 2)
            for fd,event in events:
                if fd==server_socket.fileno():
                    client_socket, client_addr = server_socket.accept()#代表有新链接来到
                    epoll.register(client_socket.fileno(),select.EPOLLIN)
                    self.user_dict[client_socket.fileno()]=client_socket
                    print('用户链接成功,当前用户为',len(self.user_dict),'个')
                else:
                    if fd in self.user_dict:
                        data_bytes = self.user_dict[fd].recv(128)
                        if data_bytes:
                           for i in self.user_dict:
                               if i!=fd:
                                   self.user_dict[i].send(data_bytes)
                        else:
                            print("断开链接,当前用户为",len(self.user_dict)-1,'个')
                            epoll.unregister(fd)
                            self.user_dict[fd].close
                            del self.user_dict[fd]
                            break

        server_socket.close()


server = Server('', 9999)
server.run()
